#!/bin/sh

# sqlplus 执行的 sql 文件的路径
query=$1
# sqlplus 登录的 ORACLE_SID
sid=$2
# sqlplus 其他参数，使用;为分隔符
parameters=$3

if [ -z "$query" ];then
    echo "Usage: $0 {<query> <sid> [parameters...]}"
    exit 1
fi

if [ -z "$sid" ];then
    echo "Usage: $0 {<query> <sid> [parameters...]}"
    exit 1
fi

os=`uname -s`
awkc=awk
if [ "$os" = "SunOS" ]; then
   awkc=nawk
fi

orauser=${LB_ORACLE_USER}
if [ -z "$orauser" ];then
  orauser=`ps -ef | grep ora_pmon | grep -v "grep" | head -n1 | sed -e 's/^[ \t]*//' | cut -d" " -f1`
fi
if [ -z "$orauser" ];then
    orauser=oracle
fi

user_id=`id ${orauser}`
if [ -z "$user_id" ];then
    echo "can't find user: ${orauser}"
    exit 1
fi

oraclehome=${LB_ORACLE_HOME}
if [ -z "$oraclehome" ];then
    oraclehome=`cat /etc/oratab | grep ${sid} | grep -v "^#" | cut -d":" -f2 | head -1`
fi
if [ -z "$oraclehome" ];then
    oraclehome=`ps -ef | grep tns | grep -v grep | grep -i listener | $awkc NR==1 | $awkc -F"/bin" '{print $(NF-1)}' | $awkc '{print $NF}'`
fi
if [ -z "$oraclehome" ];then
    oraclehome=`su - $orauser -c "echo \$ORACLE_HOME"`
fi

listener=${oraclehome}/network/admin
TNS_ADMIN=${listener}

PATH=${oraclehome}/bin:$PATH
ORACLE_HOME=${oraclehome}
ORACLE_SID=${sid}
LD_LIBRARY_PATH=${oraclehome}/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}

export PATH
export ORACLE_SID
export ORACLE_HOME
export TNS_ADMIN
export LD_LIBRARY_PATH

# set +x
Sqlplus=${oraclehome}/bin/sqlplus
if [ `echo ${query} | awk -F" " '{print $2}'` ];then
    if [ -f `echo ${query} |awk -F" " '{print $1}'` ];then
	    grp=`id -gn ${orauser}`
		par=`echo ${query} |awk -F" " '{print $2}'`
		quy=`echo ${query} |awk -F" " '{print $1}'`
		if [ -z "$grp" ]; then
            echo "failed to get group for ${orauser}"
            return 1
        fi
    	chown ${orauser}:${grp} ${quy}
    	chmod 755 ${quy}
		query="${quy} $par"
	else
		echo "error"
		exit 1;
	fi
else
	if [ -f "$query" ]; then
		grp=`id -gn ${orauser}`
    	if [ -z "$grp" ]; then
       		echo "failed to get group for ${orauser}"
       		return 1
    	fi
    	chown ${orauser}:${grp} ${query}
    	chmod 755 ${query}
	else
		exit 1;
	fi
fi

if [ -n "$parameters" ];then
  params=`echo "${parameters}" | tr ';' ' '`
	query="$query ${params}"
fi

retval=`su - ${orauser} -c "${Sqlplus} -s -L / as sysdba | grep -vi connected" << EOF
set pages 0
set head off
set feed off
set verify off
set timing off
set termout on
@${query};
exit;
EOF`

echo ${retval}